/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: KlineUtils.java
 *   @Date: 18-11-29 下午4:05
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.utils;

import android.content.Context;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import org.greenrobot.eventbus.EventBus;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import io.bhex.app.R;
import io.bhex.app.enums.PRICE_TYPE;
import io.bhex.app.event.FavoriteChangeEvent;
import io.bhex.app.market.bean.FavoriteRecordBean;
import io.bhex.app.market.bean.SearchRecordBean;
import io.bhex.baselib.constant.AppData;
import io.bhex.baselib.network.Utils.Convert;
import io.bhex.baselib.utils.SP;
import io.bhex.sdk.data_manager.MMKVManager;
import io.bhex.sdk.data_manager.SymbolDataManager;
import io.bhex.sdk.enums.COIN_TYPE;
import io.bhex.sdk.enums.ORDER_ENTRUST_TYPE;
import io.bhex.sdk.enums.ORDER_SIDE;
import io.bhex.sdk.enums.PLAN_ORDER_ENTRUST_TYPE;
import io.bhex.sdk.quote.bean.CoinPairBean;
import io.bhex.sdk.quote.bean.FuturensBaseToken;
import io.bhex.sdk.trade.bean.OrderBean;
import io.bhex.sdk.trade.futures.bean.DeliveryOrder;
import io.bhex.sdk.trade.futures.bean.FuturesOrderResponse;

public class KlineUtils {

    /**
     * 判断是否是 币币-币种
     *
     * @param coinType
     * @return
     */
    public static boolean isSymbolOfBB(int coinType) {
        return coinType == COIN_TYPE.COIN_TYPE_BB.getCoinType();
    }

    /**
     * 判断是否是 期权-币种
     *
     * @param coinType
     * @return
     */
    public static boolean isSymbolOfOption(int coinType) {
        return coinType == COIN_TYPE.COIN_TYPE_OPTION.getCoinType();
    }

    /**
     * 判断是否是 合约-币种
     *
     * @param coinType
     * @return
     */
    public static boolean isSymbolOfFutures(int coinType) {
        return coinType == COIN_TYPE.COIN_TYPE_PERPETUAL_CONTRACT.getCoinType();
    }


    /**
     * 计算涨跌量
     *
     * @param close
     * @param open
     * @return
     */
    public static float calRiseFallAmountFloat(String close, String open) {
        close = TextUtils.isEmpty(close) ? "0" : close;
        open = TextUtils.isEmpty(open) ? "0" : open;
        float closeF = Float.valueOf(close);
        float openF = Float.valueOf(open);
        return closeF - openF;
    }

    /**
     * 计算涨跌量
     *
     * @param close
     * @param open
     * @return
     */
    public static String calRiseFallAmount(String close, String open) {
        close = TextUtils.isEmpty(close) ? "0" : close;
        open = TextUtils.isEmpty(open) ? "0" : open;
        float closeF = Float.valueOf(close);
        float openF = Float.valueOf(open);
        return String.valueOf(closeF - openF);
    }

    /**
     * 计算涨跌幅
     *
     * @param close
     * @param open
     * @return
     */
    public static String calRiseFallRatio(String close, String open) {
        close = TextUtils.isEmpty(close) ? "0" : close;
        open = TextUtils.isEmpty(open) ? "0" : open;
        float closeF = Float.valueOf(close);
        float openF = Float.valueOf(open);
        if (openF > 0) {

//            float riseFallRatio = (closeF - openF) / openF;

            double riseFallRatio = NumberUtils.div(open, String.valueOf(NumberUtils.sub(close, open)));
            String s = " ";
            if (riseFallRatio > 0) {
                s = "+";
            } else if (riseFallRatio < 0) {
//            s = "-";
            }
            String ratio = NumberUtils.roundFormatDown(riseFallRatio * 100, 2);
            if (TextUtils.isEmpty(ratio)) {
                ratio = "0.00";
            }
            return s + ratio + "%";
        } else {
            return "--";
        }
    }

    /**
     * 设置行情textView颜色
     *
     * @param riseFallAmount
     * @param textView
     */
    public static void setMarketViewColor(float riseFallAmount, TextView textView) {
        if (riseFallAmount > 0) {
            textView.setTextColor(textView.getContext().getResources().getColor(R.color.green));
        } else if (riseFallAmount < 0) {
            textView.setTextColor(textView.getContext().getResources().getColor(R.color.red));
        } else {
            textView.setTextColor(textView.getContext().getResources().getColor(R.color.green));
        }
    }

    /**
     * 设置行情textView颜色
     *
     * @param riseFallAmount
     * @param view
     */
    public static void setMarketViewBgColor(float riseFallAmount, View view) {
        if (riseFallAmount > 0) {
            view.setBackgroundDrawable(ContextCompat.getDrawable(view.getContext(), R.drawable.bg_corner_green));
        } else if (riseFallAmount < 0) {
            view.setBackgroundDrawable(ContextCompat.getDrawable(view.getContext(), R.drawable.bg_corner_red));
        } else {
            //默认是涨 绿色
            view.setBackgroundDrawable(ContextCompat.getDrawable(view.getContext(), CommonUtil.isBlackMode() ? R.drawable.bg_corner_green_night : R.drawable.bg_corner_green));
        }
    }

    /**
     * 获取行情颜色
     *
     * @param context
     */
    public static int getMarketViewColor(Context context, String close, String open) {
        float riseFallAmount = calRiseFallAmountFloat(close, open);
        if (riseFallAmount > 0) {
            return context.getResources().getColor(R.color.green);
        } else if (riseFallAmount < 0) {
            return context.getResources().getColor(R.color.red);
        } else {
            return context.getResources().getColor(R.color.green);
        }
    }

    /**
     * 获取行情颜色
     *
     * @param context
     * @param riseFallAmount
     */
    public static int getMarketViewColor(Context context, float riseFallAmount) {
        if (riseFallAmount > 0) {
            return context.getResources().getColor(R.color.green);
        } else if (riseFallAmount < 0) {
            return context.getResources().getColor(R.color.red);
        } else {
            return context.getResources().getColor(R.color.green);
        }
    }

    /**
     * 清空搜索记录
     */
    public static void clearSearchRecord() {
        SP.remove(AppData.SPKEY.SEARCH_COINPAIR);
    }

    /**
     * 保存搜索
     *
     * @param item
     */
    public static void saveSearchRecord(CoinPairBean item) {
        //默认不存在
        boolean isExist = false;
        SearchRecordBean searchRecord = getSearchRecord();
        List<CoinPairBean> datas = searchRecord.getData();
        if (datas != null) {
            for (CoinPairBean data : datas) {
                if (data.getSymbolId().equals(item.getSymbolId())) {
                    isExist = true;
                }
            }
            if (!isExist) {
                datas.add(item);
            }
        } else {
            datas = new ArrayList<>();
            datas.add(item);
            searchRecord.setData(datas);
        }
        String jsonStrOfFavorite = Convert.toJson(searchRecord);

        SP.set(AppData.SPKEY.SEARCH_COINPAIR, jsonStrOfFavorite);
    }

    /**
     * 获取搜索记录
     */
    public static SearchRecordBean getSearchRecord() {
        SearchRecordBean searchRecord;
        try {
            String favoriteStr = SP.get(AppData.SPKEY.SEARCH_COINPAIR, "");
            searchRecord = Convert.fromJson(favoriteStr, SearchRecordBean.class);
            if (searchRecord != null) {
                return searchRecord;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        searchRecord = new SearchRecordBean();
        return searchRecord;
    }

    /**
     * 清空本地自选记录
     */
    public static void clearFavoriteRecord() {
        SP.remove(AppData.SPKEY.FAVORITE_COINPAIR);
    }

    /**
     * 保存自选
     *
     * @param item
     */
    public static void saveFavorite(CoinPairBean item) {
        try {
            //默认不存在
            boolean isExist = false;
            FavoriteRecordBean favoriteRecordBean = getOldFavorite();
            List<CoinPairBean> datas = favoriteRecordBean.getData();
            if (datas != null) {
                for (CoinPairBean data : datas) {
                    if (data.getSymbolId().equals(item.getSymbolId())) {
                        //本地自选列表存储里有
                        isExist = true;
                        if (!item.isFavorite()) {
                            datas.remove(data);
                        } else {
                            data.setFavorite(true);
                        }
                        break;
                    }
                }
                boolean favorite = item.isFavorite();
                if (!isExist && favorite) {
                    datas.add(item);
                }
                favoriteRecordBean.setData(datas);
            } else {
                if (item.isFavorite()) {
                    datas = new ArrayList<>();
                    datas.add(item);
                    favoriteRecordBean.setData(datas);
                }
            }
            String jsonStrOfFavorite = Convert.toJson(favoriteRecordBean);

            MMKVManager.getInstance().mmkvCacheConfig().encode(AppData.SPKEY.FAVORITE_COINPAIR, jsonStrOfFavorite);
            FavoriteChangeEvent favoriteChangeEvent = new FavoriteChangeEvent();
            favoriteChangeEvent.setCoin(item);
            /**通知更新自选列表***/
            EventBus.getDefault().post(favoriteChangeEvent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 保存自选
     *
     * @param datas
     */
    public static void saveFavorite(List<CoinPairBean> datas) {
        try {
            if (datas != null) {
                FavoriteRecordBean favoriteRecordBean = getFavorite();
                favoriteRecordBean.setData(datas);
                String jsonStrOfFavorite = Convert.toJson(favoriteRecordBean);

                MMKVManager.getInstance().mmkvCacheConfig().encode(AppData.SPKEY.FAVORITE_COINPAIR, jsonStrOfFavorite);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取自选
     */
    public static FavoriteRecordBean getFavorite() {
        FavoriteRecordBean favoriteRecordBean;
        try {
            if (!MMKVManager.getInstance().mmkvCacheConfig().containsKey(AppData.SPKEY.FAVORITE_COINPAIR)) {
                //首次没有，同步一次旧的sp缓存数据
                String oldFavoriteStr = SP.get(AppData.SPKEY.FAVORITE_COINPAIR, "");
                MMKVManager.getInstance().mmkvCacheConfig().encode(AppData.SPKEY.FAVORITE_COINPAIR, oldFavoriteStr);
            }

            String favoriteStr = MMKVManager.getInstance().mmkvCacheConfig().decodeString(AppData.SPKEY.FAVORITE_COINPAIR, "");
            favoriteRecordBean = Convert.fromJson(favoriteStr, FavoriteRecordBean.class);
            if (favoriteRecordBean != null) {
                List<CoinPairBean> data = favoriteRecordBean.getData();
                SymbolDataManager.GetInstance().setLocalFavoriteMap(data);

                return favoriteRecordBean;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        favoriteRecordBean = new FavoriteRecordBean();
        return favoriteRecordBean;
    }

    /**
     * 获取自选
     */
    public static FavoriteRecordBean getOldFavorite() {
        FavoriteRecordBean favoriteRecordBean;
        try {
            if (!MMKVManager.getInstance().mmkvCacheConfig().containsKey(AppData.SPKEY.FAVORITE_COINPAIR)) {
                //首次没有，同步一次旧的sp缓存数据
                String oldFavoriteStr = SP.get(AppData.SPKEY.FAVORITE_COINPAIR, "");
                MMKVManager.getInstance().mmkvCacheConfig().encode(AppData.SPKEY.FAVORITE_COINPAIR, oldFavoriteStr);
            }

            String favoriteStr = MMKVManager.getInstance().mmkvCacheConfig().decodeString(AppData.SPKEY.FAVORITE_COINPAIR, "");

            favoriteRecordBean = Convert.fromJson(favoriteStr, FavoriteRecordBean.class);
            if (favoriteRecordBean != null) {
                List<CoinPairBean> data = favoriteRecordBean.getData();

                return favoriteRecordBean;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        favoriteRecordBean = new FavoriteRecordBean();
        return favoriteRecordBean;
    }

    /**
     * 计算法币价格
     * @param quoteToken
     * @param price
     */
/*    public static String calLegalMoney(Context context, String quoteToken, String price) {
        String money="";
        if (TextUtils.isEmpty(quoteToken)||TextUtils.isEmpty(price)||"null".equals(price)){
            return money;
        }
        if (AppData.currentRateMap != null) {
            RatesResponse.RateBean rateBean = AppData.currentRateMap.get(quoteToken);
            if (rateBean != null) {
                String rate;
                if (DevicesUtil.isZh(context)) {
                    rate = rateBean.getCNY();
                }else{
                    rate = rateBean.getUSD();
                }
//                float legalCurrencyF = new BigDecimal(price).multiply(new BigDecimal(rate)).floatValue();
                double legalCurrencyF = NumberUtils.mul(price,rate);
                money = String.valueOf(legalCurrencyF);
            }
            return money;
        }else{
            //如果没有汇率就在取一次
            MarketApi.getRates(new MarketApi.CallBack() {
                @Override
                public void success(Object obj) {

                }

                @Override
                public void failed() {

                }
            });
            return money;
        }
    }*/

    /**
     * 转换法币显示样式 以及格式化小数位数
     * @param context
     * @param legalMoney
     * @param digitNum
     *
     *     ≈
     */
/*    public static String getShowLegalMoney(Context context, String legalMoney, int digitNum) {
        legalMoney = NumberUtils.roundFormatDown(legalMoney,digitNum);
        if (DevicesUtil.isZh(context)) {
            legalMoney = "¥"+legalMoney;
        }else{
            legalMoney = "$"+legalMoney;
        }

        return legalMoney;
    }*/

    /**
     * 获取买入卖出文案
     *
     * @param context
     * @param side
     * @return
     */
    public static String getBuyOrSellTxt(Context context, String side) {
        if (side.equals("BUY")) {
            return context.getString(R.string.string_purchase);
        } else {
            return context.getString(R.string.string_sellout);
        }
    }

    /**
     * 是否是买入方向订单
     *
     * @param context
     * @param side
     * @return
     */
    public static boolean isBuyOrder(Context context, String side) {
        if (side.equals("BUY")) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取买入卖出文案
     *
     * @param context
     * @param side
     * @return
     */
    public static String getOptionBuyOrSellTxt(Context context, String side) {
        if (side.equals("BUY")) {
//            return context.getString(R.string.string_option_purchase);
            return context.getString(R.string.string_purchase);
        } else {
//            return context.getString(R.string.string_option_sellout);
            return context.getString(R.string.string_sellout);
        }
    }

    public static String getOptionBuyOrSellTxt(Context context, boolean buy) {
        if (buy == true) {
//            return context.getString(R.string.string_option_purchase);
            return context.getString(R.string.string_purchase);
        } else {
//            return context.getString(R.string.string_option_sellout);
            return context.getString(R.string.string_sellout);
        }
    }

    /**
     * 获取买入卖出颜色
     *
     * @param context
     * @param side
     * @return
     */
    public static int getBuyOrSellColor(Context context, String side) {
        if (side.equals("BUY")) {
            return context.getResources().getColor(R.color.green);
        } else {
            return context.getResources().getColor(R.color.red);
        }
    }

    public static int getBuyOrSellColor(Context context, boolean buy) {
        if (buy == true) {
            return context.getResources().getColor(R.color.green);
        } else {
            return context.getResources().getColor(R.color.red);
        }
    }

    /**
     * 收益颜色值
     * @param context
     * @param profit
     */
    public static int getProfitColor(Context context,String profit) {
        double result = NumberUtils.sub(profit, "0");
        if (result>0) {
            return context.getResources().getColor(R.color.green);
        }else if(result == 0){
            return context.getResources().getColor(R.color.dark);
        }else{
            return context.getResources().getColor(R.color.red);
        }
    }

    /**
     * 获取合约订单方向文案
     *
     * @param context
     * @param side
     * @return
     */
    public static boolean isFuturesOpenOrder(Context context, String side) {
        if (side.equals("BUY_OPEN")) {
            return true;
        } else if (side.equals("SELL_OPEN")) {
            return true;
        }
        return false;
    }

    /**
     * 获取合约订单方向文案
     *
     * @param context
     * @param side
     * @return
     */
    public static String getFuturesOrderSideTxt(Context context, String side) {
        if (side.equals("BUY_OPEN")) {
            return context.getString(R.string.string_futures_open_long);
        } else if (side.equals("SELL_OPEN")) {
            return context.getString(R.string.string_futures_open_short);
        } else if (side.equals("BUY_CLOSE")) {
            return context.getString(R.string.string_futures_close_short);
        } else if (side.equals("SELL_CLOSE")) {
            return context.getString(R.string.string_futures_close_long);
        }
        return "";
    }

    /**
     * 是否是合约做多long订单方向
     *
     * @param
     * @param side
     * @return
     */
    public static boolean isFuturesLongOrder(String side) {
        if (side.equals("BUY_OPEN") || side.equals("SELL_CLOSE")) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 是否是合约订单-买方向
     *
     * @param context
     * @param side
     * @return
     */
    public static boolean isFuturesBuyOrder(Context context, String side) {
        if (side.equals("BUY_OPEN")) {
            return true;
        } else if (side.equals("SELL_OPEN")) {
            return false;
        } else if (side.equals("BUY_CLOSE")) {
            return true;
        } else if (side.equals("SELL_CLOSE")) {
            return false;
        }
        return true;
    }

    /**
     * 获取合约订单方向颜色
     *
     * @param context
     * @param side
     * @return
     */
    public static int getFuturesOrderSideColor(Context context, String side) {
        if (side.equals("BUY_OPEN")) {
            return context.getResources().getColor(R.color.green);
        } else if (side.equals("SELL_OPEN")) {
            return context.getResources().getColor(R.color.red);
        } else if (side.equals("BUY_CLOSE")) {
            return context.getResources().getColor(R.color.green);
        } else if (side.equals("SELL_CLOSE")) {
            return context.getResources().getColor(R.color.red);
        }
        return SkinColorUtil.getDark(context);
    }

    /**
     * 获取合约订单类型 是否是平仓单
     *
     * @param context
     * @param side
     * @return
     */
    public static boolean isFuturesCloseOrder(Context context, String side) {
        if (side.equals("BUY_CLOSE") || side.equals("SELL_CLOSE")) {
            return true;
        }else{
            return false;
        }
    }

    /**
     * 获取合约订单方向颜色
     *
     * @param context
     * @param isLong
     * @return
     */
    public static String getFuturesOpenSideByIsLong(Context context, String isLong) {
        if (isLong.equals("1")) {
            return ORDER_SIDE.BUY_OPEN.getOrderSide();
        } else {
            return ORDER_SIDE.SELL_OPEN.getOrderSide();
        }
    }

    /**
     * 获取合约订单方向文案
     *
     * @param context
     * @param isLong
     * @return
     */
    public static String getFuturesOrderSideTxtByIsLong(Context context, String isLong) {
        if (isLong.equals("1")) {
            return context.getString(R.string.string_futures_open_long);
        } else {
            return context.getString(R.string.string_futures_open_short);
        }
    }

    /**
     * 获取合约订单方向文案
     *
     * @param context
     * @param isLong
     * @return
     */
    public static String getFuturesOrderPositionTxtByIsLong(Context context, String isLong) {
        if (isLong.equals("1")) {
            return context.getString(R.string.string_futures_position_long);
        } else {
            return context.getString(R.string.string_futures_position_short);
        }
    }

    /**
     * 获取合约订单方向颜色
     *
     * @param context
     * @param isLong
     * @return
     */
    public static int getFuturesOrderSideColorByIsLong(Context context, String isLong) {
        if (isLong.equals("1")) {
            return context.getResources().getColor(R.color.green);
        } else {
            return context.getResources().getColor(R.color.red);
        }
    }

    /**
     * 获取合约订单方向文案-（相反）
     *
     * @param context
     * @param isLong
     * @return
     */
    public static String getFuturesOrderOppositeSideTxtByIsLong(Context context, String isLong) {
        if (isLong.equals("1")) {
            return context.getString(R.string.string_futures_close_long);
        } else {
            return context.getString(R.string.string_futures_close_short);
        }
    }

    /**
     * 获取合约订单方向颜色
     *
     * @param context
     * @param isLong
     * @return
     */
    public static int getFuturesOrderOppositeSideColorByIsLong(Context context, String isLong) {
        if (isLong.equals("1")) {
            return context.getResources().getColor(R.color.red);
        } else {
            return context.getResources().getColor(R.color.green);
        }
    }

    /**
     * 获取买入卖出类型的文案
     *
     * @param context
     * @param type
     * @return
     */
    public static String getPriceModeTxt(Context context, String type) {
        if (type.equals("LIMIT")) {
            return context.getString(R.string.string_limited_price);
        } else {
            return context.getString(R.string.string_market_price);
        }
    }

    /**
     * 获取下单价格类型
     *
     * @param context
     * @param priceType
     * @return
     */
    public static String getPriceTypeTxt(Context context, String priceType) {
        if (priceType.equals(PRICE_TYPE.INPUT.getPriceType())) {
            return context.getString(R.string.string_limited_price);
        } else if(priceType.equals(PRICE_TYPE.MARKET_PRICE.getPriceType())) {
            return context.getString(R.string.string_market_price);
        } else if(priceType.equals(PRICE_TYPE.OPPONENT.getPriceType())) {
            return context.getString(R.string.string_rival_price);
        } else if(priceType.equals(PRICE_TYPE.QUEUE.getPriceType())) {
            return context.getString(R.string.string_queuing_price);
        } else if(priceType.equals(PRICE_TYPE.OVER.getPriceType())) {
            return context.getString(R.string.string_over_price);
        }
        return "";
    }

    /**
     * 看涨看跌类型的文案
     *
     * @param context
     * @param type
     * @return
     */
    public static String getRiseOrFallTxt(Context context, String type) {
        if (type.equalsIgnoreCase("Call")) {
            return context.getString(R.string.string_option_call);
        } else {
            return context.getString(R.string.string_option_put);
        }
    }


    /**
     * 获取订单价格
     *
     * @param context
     * @param order
     * @return
     */
    public static String getPrice(Context context, OrderBean order) {
        if (order.getType().equals("LIMIT")) {
            int tokenDigit = SymbolDataManager.GetInstance().getTokenDigitBySymbolIdAndTokenId(order.getSymbolId() + order.getQuoteTokenId());
            return roundFormatDown(order.getPrice(), tokenDigit) + " " + order.getQuoteTokenName();
//            return order.getPrice()+" "+order.getQuoteTokenName();
        } else {
            return context.getString(R.string.string_market_price);
        }
    }

    /**
     * 获取订单均价
     *
     * @param context
     * @param order
     * @return
     */
    public static String getAvgPrice(Context context, OrderBean order) {
        int tokenDigit = SymbolDataManager.GetInstance().getTokenDigitBySymbolIdAndTokenId(order.getSymbolId() + order.getQuoteTokenId());
        return roundFormatDown(order.getAvgPrice(), tokenDigit) + " " + order.getQuoteTokenName();
//            return order.getPrice()+" "+order.getQuoteTokenName();
    }

    public static String getFuturesPriceUnit(String symbolId){
        String priceUnit="";
        CoinPairBean futuresSymbol = SymbolDataManager.GetInstance().getFuturesSymbolInfoById(symbolId);
        if (futuresSymbol != null) {
            FuturensBaseToken baseTokenFutures = futuresSymbol.baseTokenFutures;
            if ( baseTokenFutures!= null) {
                priceUnit = baseTokenFutures.getDisplayTokenId();
            }

        }
        return priceUnit;
    }

    /**
     * 盈亏单位
     * @param symbolId
     * @return
     */
    public static String getFuturesProfitLossUnit(String symbolId){
        String profitLossUnit="";
        CoinPairBean futuresSymbol = SymbolDataManager.GetInstance().getFuturesSymbolInfoById(symbolId);
        if (futuresSymbol != null) {
            profitLossUnit = futuresSymbol.getQuoteTokenName();

        }
        return profitLossUnit;
    }

    /**
     * 获取合约订单触发价格
     *
     * @param context
     * @param order
     * @return
     */
    public static String getFuturesTriggerPrice(Context context, FuturesOrderResponse order) {
//        int tokenDigit = SymbolDataManager.GetInstance().getTokenDigitBySymbolIdAndTokenId(order.getSymbolId() + order.getQuoteTokenId());
//        return roundFormatDown(order.getTriggerPrice(), tokenDigit) + " " + getFuturesPriceUnit(order.getSymbolId());
        return order.getTriggerPrice() + " " + getFuturesPriceUnit(order.getSymbolId());
    }

    /**
     * 获取合约订单价格
     *
     * @param context
     * @param order
     * @return
     */
    public static String getFuturesPrice(Context context, FuturesOrderResponse order) {
//        int tokenDigit = SymbolDataManager.GetInstance().getTokenDigitBySymbolIdAndTokenId(order.getSymbolId() + order.getQuoteTokenId());
//        return roundFormatDown(order.getPrice(), tokenDigit) + " " + getFuturesPriceUnit(order.getSymbolId());
        if (order.getPriceType().equals(PRICE_TYPE.MARKET_PRICE.getPriceType())) {
            return context.getResources().getString(R.string.string_market_price);
        }else{
            return order.getPrice() + " " + getFuturesPriceUnit(order.getSymbolId());
        }
    }

    /**
     * 获取合约订单均价
     *
     * @param context
     * @param order
     * @return
     */
    public static String getFuturesAvgPrice(Context context, FuturesOrderResponse order) {
//        int tokenDigit = SymbolDataManager.GetInstance().getTokenDigitBySymbolIdAndTokenId(order.getSymbolId() + order.getQuoteTokenId());
//        return roundFormatDown(order.getAvgPrice(), tokenDigit) + " " + getFuturesPriceUnit(order.getSymbolId());
        return TextUtils.isEmpty(order.getAvgPrice())?context.getResources().getString(R.string.string_placeholder):order.getAvgPrice() + " " + getFuturesPriceUnit(order.getSymbolId());
    }

    /**
     * 获取历史-止盈止损-合约订单成交均价
     *
     * @param context
     * @param order
     * @return
     */
    public static String getFuturesStopProfitOrLossExecutedPrice(Context context, FuturesOrderResponse order) {
//        int tokenDigit = SymbolDataManager.GetInstance().getTokenDigitBySymbolIdAndTokenId(order.getSymbolId() + order.getQuoteTokenId());
//        return roundFormatDown(order.getAvgPrice(), tokenDigit) + " " + getFuturesPriceUnit(order.getSymbolId());
        return TextUtils.isEmpty(order.getExecutedPrice())?context.getResources().getString(R.string.string_placeholder):order.getExecutedPrice() + " " + getFuturesPriceUnit(order.getSymbolId());
    }

    /**
     * 获取成交数量
     *
     * @param context
     * @param order
     * @return
     */
    public static String getDealAmount(Context context, OrderBean order) {
        int baseDigit = SymbolDataManager.GetInstance().getTokenDigitBySymbolIdAndTokenId(order.getSymbolId() + order.getBaseTokenId());
        return roundFormatDown(order.getExecutedQty(), baseDigit) + " " + order.getBaseTokenName();
    }

    /**
     * 获取成交金额
     *
     * @param context
     * @param order
     * @return
     */
    public static String getDealMoney(Context context, OrderBean order) {
        int amountDigit = SymbolDataManager.GetInstance().getAmountDigitBySymbolIdAndTokenId(order.getSymbolId() + order.getQuoteTokenId());
        return roundFormatDown(order.getExecutedAmount(), amountDigit) + " " + order.getQuoteTokenName();
    }

    /**
     * 根据非整8位精度规则处理
     *
     * @param num
     * @param len
     * @return
     */
    public static String roundFormatDown(String num, int len) {
        String strTemp = "";

        try {
            if (num == null || num.equals("")) {
                return strTemp;
            }
            String value8 = NumberUtils.roundFormatDown(num, AppData.Config.DIGIT_DEFAULT_VALUE);
            if (TextUtils.isEmpty(value8)) {
                value8 = "0";
            }
            if (len > 0) {
                String precision = "";
                for (int i = 0; i < len; i++) {
                    if (i == 0) {
                        if (i < len - 1) {
                            precision = precision + "0.0";
                        } else {
                            precision = precision + "0.1";
                        }

                    } else {
                        if (i != len - 1) {
                            precision = precision + "0";
                        } else {
                            precision = precision + "1";
                        }
                    }
                }
                double pow = Math.pow(10, 8);
                BigDecimal[] bigDecimals = new BigDecimal(value8).multiply(new BigDecimal(pow)).divideAndRemainder(new BigDecimal(precision).multiply(new BigDecimal(pow)));
                if (bigDecimals[1].floatValue() > 0) {
                    len = AppData.Config.DIGIT_DEFAULT_VALUE;
                }
            }

            BigDecimal b = new BigDecimal(num);
            BigDecimal f1 = b.setScale(len, BigDecimal.ROUND_DOWN);
            strTemp = f1.toPlainString();
        } catch (Exception ex) {
            ex.printStackTrace();
            strTemp = "";
        }

        return strTemp;
    }

    /**
     * 获取订单单位（根据买卖方向，价格类型）
     *
     * @param order
     * @return
     */
    public static String getTokenUnit(OrderBean order) {
        if (order != null) {
            if (!order.getType().equals("LIMIT") && order.getSide().equals("BUY")) {
                return order.getQuoteTokenName();
            } else {
                return order.getBaseTokenName();
            }
        } else {
            return "";
        }
    }


    /**
     * 获取订单单位（根据买卖方向，价格类型）
     *
     * @param order
     * @return
     */
    public static String getEntrustTitleAndUnit(Context context, OrderBean order) {
        if (order != null) {
            if (!order.getType().equals("LIMIT") && order.getSide().equals("BUY")) {
                return context.getResources().getString(R.string.string_format_entrust_amount_of_money, order.getQuoteTokenName());
            } else {
                return context.getResources().getString(R.string.string_format_entrust_amount, order.getBaseTokenName());
            }
        } else {
            return "";
        }
    }

    /**
     * 获取订单单位（根据买卖方向，价格类型）
     *
     * @param order
     * @return
     */
    public static String getEntrustTitle(Context context, OrderBean order) {
        if (order != null) {
            if (!order.getType().equals("LIMIT") && order.getSide().equals("BUY")) {
                return context.getResources().getString(R.string.string_order_entrust_amount_of_money);
            } else {
                return context.getResources().getString(R.string.string_order_entrust_amount);
            }
        } else {
            return "";
        }
    }

    /**
     * 成交量(数量或者金额)+单位（根据买卖方向，价格类型）
     *
     * @param order
     * @return
     */
    public static String getOrderDeal(OrderBean order) {
        if (order != null) {
            if (!order.getType().equals("LIMIT") && order.getSide().equals("BUY")) {
                return order.getExecutedAmount() + order.getQuoteTokenName();
            } else {
                return order.getExecutedQty() + order.getBaseTokenName();
            }
        } else {
            return "";
        }
    }

    /**
     * 委托量（根据买卖方向，价格类型）
     *
     * @param order
     * @return
     */
    public static String getOrderEntrust(OrderBean order) {
        if (order != null) {
            if (!order.getType().equals("LIMIT") && order.getSide().equals("BUY")) {
                return order.getOrigQty();
//                return order.getOrigQty()+order.getQuoteTokenName();
            } else {
                return order.getOrigQty();
//                return order.getOrigQty()+order.getBaseTokenName();
            }
        } else {
            return "";
        }
    }

    /**
     * 委托量+单位（根据买卖方向，价格类型）
     *
     * @param order
     * @return
     */
    public static String getOrderEntrustAndUnit(OrderBean order) {
        if (order != null) {
            if (!order.getType().equals("LIMIT") && order.getSide().equals("BUY")) {
                int amountDigit = SymbolDataManager.GetInstance().getAmountDigitBySymbolIdAndTokenId(order.getSymbolId() + order.getQuoteTokenId());
                return roundFormatDown(order.getOrigQty(), amountDigit) + " " + order.getQuoteTokenName();
            } else {
                int baseDigit = SymbolDataManager.GetInstance().getTokenDigitBySymbolIdAndTokenId(order.getSymbolId() + order.getBaseTokenId());
                return roundFormatDown(order.getOrigQty(), baseDigit) + " " + order.getBaseTokenName();
            }
        } else {
            return "";
        }
    }

    /**
     * 订单状态解释
     *
     * @param context
     * @param order
     * @return
     */
    public static String getOrderStatus(Context context, OrderBean order) {
        String status = order.getStatus();
        if (!TextUtils.isEmpty(status)) {
            if (status.equals("FILLED")) {
                return context.getResources().getString(R.string.string_deal_all);
            } else if (status.equals("CANCELED")) {
                String executedQty = order.getExecutedQty();
                if (!TextUtils.isEmpty(executedQty) && Float.valueOf(executedQty) > 0) {
                    return context.getResources().getString(R.string.string_deal_part);
                } else {
                    return context.getResources().getString(R.string.string_revoked);
                }
            }
            return status;

        } else {
            return "";
        }
    }

    /**
     * 是否是期货强平成交订单
     * @param context
     * @param order
     * @return
     */
    public static boolean isFuturesForceCLoseTradeOrder(Context context, DeliveryOrder order) {
        String liquidationType = order.getLiquidationType(); // 爆仓单类型 NO_LIQ非爆仓单 IOC爆仓强平单 ADL爆仓减仓单
        if (!TextUtils.isEmpty(liquidationType)) {
            if (liquidationType.equalsIgnoreCase("IOC")) {
                return true;
            }
        }
        return false;
    }

    /**
     * 是否是期货强平委托订单
     * @param context
     * @param order
     * @return
     */
    public static boolean isFuturesForceCLoseOrder(Context context, FuturesOrderResponse order) {
        String liquidationType = order.getLiquidationType(); // 爆仓单类型 NO_LIQ非爆仓单 IOC爆仓强平单 ADL爆仓减仓单
        if (!TextUtils.isEmpty(liquidationType)) {
            if (liquidationType.equalsIgnoreCase("IOC")) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取期货订单状态颜色
     * @param context
     * @param order
     * @return
     */
    public static int getFuturesOrderStatusColor(Context context, FuturesOrderResponse order) {
        String liquidationType = order.getLiquidationType(); // 爆仓单类型 NO_LIQ非爆仓单 IOC爆仓强平单 ADL爆仓减仓单
        if (!TextUtils.isEmpty(liquidationType)) {
            if (liquidationType.equalsIgnoreCase("IOC")) {
                return context.getResources().getColor(R.color.red);
            } else if (liquidationType.equalsIgnoreCase("ADL")) {
                return context.getResources().getColor(R.color.green);
            }
        }
        return SkinColorUtil.getDark(context);
    }

    /**
     * 订单状态解释
     *
     * @param context
     * @param order
     * @return //普通委托-订单状态 (NEW 订单已创建 PARTIALLY_FILLED 部分成交FILLED 完全成交 CANCELED 已取消 REJECTED 已拒绝
     * //计划委托-订单状态. ORDER_NEW=等待委托，ORDER_FILLED=已委托，ORDER_REJECTED=委托失败，ORDER_CANCELED=委托取消
     */
    public static String getFuturesOrderStatus(Context context, FuturesOrderResponse order) {
        String liquidationType = order.getLiquidationType(); // 爆仓单类型 NO_LIQ非爆仓单 IOC爆仓强平单 ADL爆仓减仓单
        if (!TextUtils.isEmpty(liquidationType)) {
            if (liquidationType.equalsIgnoreCase("IOC")) {
                return context.getResources().getString(R.string.string_force_close);
            }else if(liquidationType.equalsIgnoreCase("ADL")){
                return context.getResources().getString(R.string.string_force_reduce_position);
            }
        }
        String status = order.getStatus();
        if (!TextUtils.isEmpty(status)) {
            if (order.getType().equals(ORDER_ENTRUST_TYPE.LIMIT.getEntrustType())) {
                if (status.equals("NEW")) {
                    return context.getResources().getString(R.string.string_order_new_status);
                } else if (status.equals("PARTIALLY_FILLED")) {
                    return context.getResources().getString(R.string.string_deal_part);
                } else if (status.equals("FILLED")) {
                    return context.getResources().getString(R.string.string_deal_all);
                } else if (status.equals("CANCELED")) {
                    return context.getResources().getString(R.string.string_revoked);
                } else if (status.equals("REJECTED")) {
                    return context.getResources().getString(R.string.string_rejected);
                }
            } else {
                if (status.equals("ORDER_NEW")) {
                    return context.getResources().getString(R.string.string_order_status_waiting_entrust);
                } else if (status.equals("ORDER_FILLED")) {
                    return context.getResources().getString(R.string.string_order_status_filled);
                } else if (status.equals("ORDER_REJECTED")) {
                    return context.getResources().getString(R.string.string_order_status_entrust_failed);
                } else if (status.equals("ORDER_CANCELED")) {
                    return context.getResources().getString(R.string.string_order_status_entrust_canceled);
                }
            }
            return status;

        } else {
            return "";
        }
    }

    /**
     * 判断是否是风险资产token  默认BTC USDT ETH
     *
     * @param tokenId
     * @return
     */
    public static boolean isRiskTokenId(String tokenId) {
        return tokenId.equalsIgnoreCase("BTC") || tokenId.equalsIgnoreCase("USDT") || tokenId.equalsIgnoreCase("ETH");
    }

    /**
     * 判断期权是否是看涨
     *
     * @param isCall
     * @return true 看涨   false 看跌
     */
    public static boolean isOptionCall(String isCall) {
        if (isCall.equalsIgnoreCase("1")) {
            return true;
        } else if (isCall.equalsIgnoreCase("0")) {
            return false;
        }
        return true;
    }

    /**
     * 止盈止损订单类型
     * @param context
     * @param planOrderType
     * @return
     */
    public static String getPlanOrderTypeTxt(Context context, String planOrderType) {
        if (planOrderType.equals(PLAN_ORDER_ENTRUST_TYPE.STOP_COMMON.getEntrustType())) {
            return context.getString(R.string.string_planning_entrument);
        } else if(planOrderType.equals(PLAN_ORDER_ENTRUST_TYPE.STOP_LONG_PROFIT.getEntrustType())) {
            return context.getString(R.string.string_stop_profit);
        } else if(planOrderType.equals(PLAN_ORDER_ENTRUST_TYPE.STOP_LONG_LOSS.getEntrustType())) {
            return context.getString(R.string.string_stop_loss);
        } else if(planOrderType.equals(PLAN_ORDER_ENTRUST_TYPE.STOP_SHORT_PROFIT.getEntrustType())) {
            return context.getString(R.string.string_stop_profit);
        } else if(planOrderType.equals(PLAN_ORDER_ENTRUST_TYPE.STOP_SHORT_LOSS.getEntrustType())) {
            return context.getString(R.string.string_stop_loss);
        }
        return "";
    }

    /**
     * 是否是 - 止盈委托单
     * @param planOrderType
     * @return
     */
    public static boolean isStopProfitOrder(String planOrderType) {
        if(planOrderType.equals(PLAN_ORDER_ENTRUST_TYPE.STOP_LONG_PROFIT.getEntrustType()) || planOrderType.equals(PLAN_ORDER_ENTRUST_TYPE.STOP_SHORT_PROFIT.getEntrustType())) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 是否是 - 普通的计划委托（非止盈止损订单）
     * @param itemModel
     */
    public static boolean isStopCommonOrder(FuturesOrderResponse itemModel) {
        if (TextUtils.isEmpty(itemModel.getPlanOrderType())) {
            //为空 是普通委托
            return true;
        }
        String planOrderType = itemModel.getPlanOrderType();
        if(planOrderType.equals(PLAN_ORDER_ENTRUST_TYPE.STOP_COMMON.getEntrustType())) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 是否是 - 止盈止损订单
     * @param itemModel
     */
    public static boolean isStopProfitOrLossOrder(FuturesOrderResponse itemModel) {
        if (itemModel.getType().equals(ORDER_ENTRUST_TYPE.STOP.getEntrustType())) {
            String planOrderType = itemModel.getPlanOrderType();
            if(!planOrderType.equals(PLAN_ORDER_ENTRUST_TYPE.STOP_COMMON.getEntrustType())) {
                return true;
            }
        }
        return false;
    }
}
